import pygame
import player
import ball
import draw
from defs import *

#~ levels  = defs.levels
class Game():
    #~ def __init__(self):
        #~ self.currentLevel = 0

    def __init__(self, player1, player2, ball, draw):
        self.currentLevel = 0
        self.player1 = player1
        self.player2 = player2
        self.ball = ball
        self.draw = draw
        
        # State
        self.done       = False
        self.move       = False
        self.started    = False
        self.pause      = False
        self.menu       = True
        
        # Options
        self.music      = True
        
        # Points
        self.pointsP1 = 0
        self.pointsP2 = 0

        # Timer
        self.gameTimer = 0
        self.levelTimer = 0
        
        self.startMusic()
    
    def startMusic(self):        
        music_file = "midi/ff6-decisive.mp3"

        pygame.mixer.music.load(music_file)
        pygame.mixer.music.play()
    
    # Level
    def resetLevel(self):
        self.currentLevel = 0
        self.updateLevel()

    def nextLevel(self):
        self.currentLevel += 1
        self.updateLevel()

    def previousLevel(self):
        self.currentLevel -= 1
        self.updateLevel()    
    
    def updateLevel(self):
        lvl = self.currentLevel
        # No more levels
        if lvl >= len(levels):
            self.currentLevel = len(levels) - 1
            return
            
        if lvl < 0:
            self.currentLevel = 0
            return

        self.ball.increaseSpeed(levels[lvl][0], levels[lvl][1])

        self.player1.height += levels[lvl][2]
        self.player2.height += levels[lvl][3]

        if ai:
            self.player1.ai_speed += levels[lvl][4]
        else:
            self.player1.speed_rate += levels[lvl][4]
        self.player2.speed_rate += levels[lvl][5]

        print "Level", str(self.currentLevel)


    def setClock(self, clock):
        self.clock = clock

    def setNumFont(self, font):
        self.numFont = font

    def setTimerFont(self, font):
        self.timerFont = font
        
    def setPauseFont(self, font):
        self.pauseFont = font

    def start(self):  
        self.draw.update()
        self.startMenu()
        
        while self.menu:            
            self.processInput()
                
        if not pygame.mixer.music.get_busy():
                pygame.mixer.music.play()
        
        while not self.done:    
            #~ if not pygame.mixer.music.get_busy():
                #~ pygame.mixer.music.play()
            
            self.processInput()
            
            if not self.pause:            
                if self.move:
                    self.updatePlayerPosition()
                self.setPlayerPosition()
                if self.move:
                    self.updateObjectPosition()

                # ----- Begin Drawing Something -----
                #~ Si usamos las paletas normales va esto
                self.draw.setRect([self.player1_rect, self.player2_rect])
                self.draw.updateSpritePosition([self.ball.getPosition()])
                self.draw.renderNumber(self.numFont, \
                                    [self.pointsP1, self.pointsP2])        
                self.draw.renderTime(self.timerFont, \
                            [[self.levelTimer, "Level Time: "], \
                            [self.gameTimer, "Total Time: "]])
                self.draw.updateLevel(self.currentLevel + 1, self.numFont)
                self.draw.update()
                # ----- End Drawing Something -----
            
            # Limit to fps frames per second
            self.clock.tick(fps)
            if not self.pause and self.started:
                self.gameTimer += tick
            if not self.pause and self.move:
                self.levelTimer += tick              
              

    def startMenu(self):
        self.draw.dim()        
        self.draw.updateMenu(self.numFont)
    
    def reset(self):
        self.move = False
        self.ball.reset()
        self.player1.reset()
        self.player2.reset()
        self.levelTimer = 0

    # Updates player positions
    def updatePlayerPosition(self):
        if ai:
            self.player1.update(self.ball.getPosition()[1], self.ball.getSpeed()[0])
        self.player1.updatePosition()
        self.player2.updatePosition()

    def setPlayerPosition(self):
        self.player1_rect = self.player1.getRect()
        self.player2_rect = self.player2.getRect()

    # Updates ball positions and state
    def updateObjectPosition(self):
        state = self.ball.update(self.player1_rect, self.player2_rect)
        if state[0]:
            if state[1] == 1:
                self.pointsP2 += 1                
                self.nextLevel()
                #~ if not ai and 
            else:
                self.pointsP1 += 1
                # If player2 is losing too much go back a level
                if (self.pointsP1 - self.pointsP2) > 5:
                    self.previousLevel()                    
            self.reset()


    # Process input (keyboard, mouse, joystick, etc)
    def processInput(self):
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                self.done = True
                break

            if event.type == pygame.KEYDOWN:
                self.processPressedKey(event.key)

            if event.type == pygame.KEYUP:
                self.processReleasedKey(event.key)
	
    def mute(self):
		self.music = not self.music
		if not self.music:
			pygame.mixer.music.pause()
		else:
			pygame.mixer.music.unpause()
		
    def processPressedKey(self, key):
        if (key == pygame.K_ESCAPE or key == pygame.K_p):            
            self.pause = not self.pause
            if self.pause:
                self.draw.dim()               
                self.draw.updatePause(self.pauseFont)        
                pygame.mixer.music.pause()
            elif self.music:
				pygame.mixer.music.unpause()

        if not self.pause and key == pygame.K_l:
            self.nextLevel()
            
        # See Controls
        if key == pygame.K_c:
            self.pause = not self.pause
            if self.pause:
                self.startMenu()
            
        if not self.pause and key == pygame.K_r:
            self.reset()

        # Mute
        if not self.pause and key == pygame.K_m:            
            self.mute() 
        
        # Movement
        if not self.move:       
            if key == pygame.K_SPACE:
                self.move = True
                self.menu = False
                # Start moving ball
                self.ball.setSpeed(ball_speed_x, ball_speed_y)
                if not self.started:
                    self.started = True

        if not self.pause and self.move:
            if key == pygame.K_UP:
                self.player2.setSpeed(-self.player2.speed_rate)
            if key == pygame.K_DOWN:
                self.player2.setSpeed(self.player2.speed_rate)
            if not ai:
                if key == pygame.K_w:
                    self.player1.setSpeed(-self.player1.speed_rate)
                if key == pygame.K_s:
                    self.player1.setSpeed(self.player1.speed_rate)

    def processReleasedKey(self, key):
        if not self.pause and self.move:
            if key == pygame.K_UP:                
                self.player2.setSpeed(0)
            if key == pygame.K_DOWN:
                self.player2.setSpeed(0)                
            if not ai:
                if key == pygame.K_w:
                    self.player1.setSpeed(0)
                if key == pygame.K_s:
                    self.player1.setSpeed(0)
